package com.lagou.controller;

import com.lagou.entity.Token;
import com.lagou.service.UserService;
import com.lagou.service.remote.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private CodeService codeService;

    /**
     * 根据token查询⽤用户登录邮箱（用于网关校验）
     *
     * @return Email
     */
    @RequestMapping("/info/{token}")
    public String info(@PathVariable("token") String token) {
        Token existedToken = userService.getToken(token);
        return existedToken != null ? existedToken.getEmail() : "";
    }

    /**
     * 注册
     *
     * @param email
     * @param password
     * @param code
     * @return 0-成功
     */
    @RequestMapping("/register/{email}/{password}/{code}")
    public int register(@PathVariable("email") String email,
                            @PathVariable("password") String password,
                            @PathVariable("code") String code,
                            HttpServletResponse response) {

        // 检查邮箱是否已经注册过
        if (userService.isEmailRegistered(email)) {
            return -1;
        }

        // 校验验证码
        int codeValidateResult = codeService.validateCode(email, code);
        if (codeValidateResult != 0) {
            return codeValidateResult;
        }

        // 生成新用户
        userService.createUser(email, password);

        // 创建Token并写入Cookie
        createTokenAndAddCookie(email, response);

        return 0;
    }

    /**
     * 登录
     *
     * @param email
     * @param password
     * @return
     */
    @RequestMapping("/login/{email}/{password}")
    public boolean login(@PathVariable("email") String email,
                        @PathVariable("password") String password,
                        HttpServletResponse response) {

        // 校验邮箱和密码
        if (!userService.checkPassword(email, password)) {
            return false;
        }

        // 生成新的Token并写入Cookie
        createTokenAndAddCookie(email, response);

        return true;
    }

    /**
     * 创建Token并写入Cookie
     *
     * @param email
     * @param response
     */
    private void createTokenAndAddCookie(String email, HttpServletResponse response) {
        Token token = userService.createToken(email);

        // Token
        Cookie tokenCookie = new Cookie("login_token", token.getToken());
        tokenCookie.setMaxAge(48 * 3600);
        tokenCookie.setPath("/");
        response.addCookie(tokenCookie);

        // Email
        Cookie loginEmailCookie = new Cookie("login_email", email);
        loginEmailCookie.setMaxAge(48 * 3600);
        loginEmailCookie.setPath("/");
        response.addCookie(loginEmailCookie);
    }

}
